package com.nnnu.wsnackshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nnnu.wsnackshop.mapper.CouponUsageMapper;
import com.nnnu.wsnackshop.pojo.entity.CouponUsage;
import com.nnnu.wsnackshop.service.ICouponUsageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 优惠券使用记录 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-06-24
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CouponUsageServiceImpl extends ServiceImpl<CouponUsageMapper, CouponUsage>
        implements ICouponUsageService {

    private final CouponUsageMapper couponUsageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean recordUsage(Integer userCouponId, Integer userId, Integer couponId, Long orderId, String orderNo,
            BigDecimal amount) {
        try {
            CouponUsage usage = new CouponUsage();
            usage.setUserCouponId(userCouponId);
            usage.setUserId(userId);
            usage.setCouponId(couponId);
            usage.setOrderId(orderId);
            usage.setOrderNo(orderNo);
            usage.setAmount(amount);
            usage.setUsedAt(LocalDateTime.now());
            usage.setCreatedAt(LocalDateTime.now());

            int result = couponUsageMapper.insert(usage);
            return result > 0;
        } catch (Exception e) {
            log.error("记录优惠券使用失败: userCouponId={}, userId={}, orderId={}, error={}",
                    userCouponId, userId, orderId, e.getMessage(), e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUsageByOrderId(Integer userId, Long orderId) {
        try {
            LambdaQueryWrapper<CouponUsage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CouponUsage::getUserId, userId)
                    .eq(CouponUsage::getOrderId, orderId);

            int result = couponUsageMapper.delete(queryWrapper);
            return result > 0;
        } catch (Exception e) {
            log.error("删除优惠券使用记录失败: userId={}, orderId={}, error={}",
                    userId, orderId, e.getMessage(), e);
            return false;
        }
    }
}